package sever

import (
	"0507zk/common/initialize"
	product "0507zk/common/proto"
	"0507zk/rpc/mysqlInit"
	"context"
	"encoding/json"
	"errors"
	"math/rand"
	"time"
)

func SendSms(in *product.SendSmsReq) (*product.SendSmsResp, error) {
	code := rand.Intn(9000) + 1000
	//err := pkg.SendSms(in.Mobile, strconv.Itoa(code))
	//if err != nil {
	//	return nil, errors.New("验证码生成错误")
	//}
	initialize.Client.Set(context.Background(), "SendSms"+in.Router+in.Mobile, code, time.Minute*2)
	return &product.SendSmsResp{Success: true}, nil
}

func UserLogin(in *product.UserLoginReq) (*product.UserLoginResp, error) {
	var u mysqlInit.User
	get := initialize.Client.Get(context.Background(), "SendSmslogin"+in.Mobile)
	if get.Val() != in.Code {
		return nil, errors.New("验证码错误,请重试")
	}
	user, err := u.GetUserMobile(in.Mobile)
	if err != nil {
		return nil, errors.New("用户信息查找失败")
	}
	if user.ID == 0 {
		return nil, errors.New("用户还未注册,请先去注册")
	}
	if user.Password != in.Password {
		return nil, errors.New("用户密码错误,请重试")
	}
	return &product.UserLoginResp{UserId: int64(user.ID)}, nil
}

var products []*mysqlInit.Product

func Product(in *product.ProductListReq) (*product.ProductListResp, error) {
	var p mysqlInit.Product
	var err error
	if in.Name != "" {
		products, err = p.GetProductName(in.Name)
		if err != nil {
			return nil, errors.New("商品查询失败")
		}
	} else {
		products, err = p.GetProduct()
		if err != nil {
			return nil, errors.New("商品查询失败")
		}

	}
	pro := []*product.ProductList{}

	for _, i := range products {
		pro = append(pro, &product.ProductList{
			PId:    int64(i.ID),
			Name:   i.Name,
			Price:  float32(i.Price),
			Stock:  int64(i.Stock),
			Status: int64(i.Status),
		})
	}

	marshal, err := json.Marshal(pro)
	if err != nil {
		return nil, errors.New("数据转换失败")
	}

	initialize.Client.Set(context.Background(), "Product:list", marshal, time.Minute)

	return &product.ProductListResp{List: pro}, nil
}
